package com.googlecode.antilopebpm.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.antilopebpm.cfg.AntilopeConfiguration;

public class ByteBlockChopper {

	/**
	 * @param byteArray
	 * @param blockType
	 *            <ul>
	 *            <li> Serializable Variable:{@link com.googlecode.antilopebpm.cfg.AntilopeConfiguration#VARIABLE_BYTE_BLOCK_SIZE}</li>
	 *            <li> Process Definition:{@link com.googlecode.antilopebpm.cfg.AntilopeConfiguration#PROCDEFINITION_BYTEARRAY_BLOCK_SIZE}</li>
	 *            <ul>
	 * @return
	 */
	public static List<byte[]> chopItUp(byte[] byteArray, String blockType) {
		int blockSize = AntilopeConfiguration.getInt(blockType);
		List<byte[]> bytes = null;
		if ((byteArray != null) && (byteArray.length > 0)) {
			bytes = new ArrayList<byte[]>();
			int index = 0;
			while ((byteArray.length - index) > blockSize) {
				byte[] byteBlock = new byte[blockSize];
				System.arraycopy(byteArray, index, byteBlock, 0, blockSize);
				bytes.add(byteBlock);
				index += blockSize;
			}
			byte[] byteBlock = new byte[byteArray.length - index];
			System.arraycopy(byteArray, index, byteBlock, 0, byteArray.length
					- index);
			bytes.add(byteBlock);
		}
		return bytes;
	}

	public static byte[] glueChopsBackTogether(List<byte[]> bytes) {
		byte[] value = null;

		if (bytes != null) {
			Iterator<byte[]> iter = bytes.iterator();
			while (iter.hasNext()) {
				byte[] byteBlock = (byte[]) iter.next();
				if (value == null) {
					value = byteBlock;
				} else {
					byte[] oldValue = value;
					value = new byte[value.length + byteBlock.length];
					System.arraycopy(oldValue, 0, value, 0, oldValue.length);
					System.arraycopy(byteBlock, 0, value, oldValue.length,
							byteBlock.length);
				}
			}
		}

		return value;
	}
}
